/*
 * InterviewTasks.cpp
 *
 *  Created on: Mar 17, 2009
 *      Author: Lev
 */

#include <iostream>
using namespace std;

/*
 * Task: Implement C function that returns 1, if the OS uses big endian format
 * and 0, if it uses little endian format (don't use standard libraries).
 */
int isBigEndian() {
	int n = 1;
	char *p = (char *)&n;
	return p[0] == 1 ? 1 : 0;
}

/*
 * Task: Implement C function that returns index of the least significant
 * set bit for a given int i (don't use standard libraries; start indexing
 * from the least significant bit).
 */
int leastSignificantSetBitIndex( int i ) {
	if( i == 0 )
		return -1; // no set bit
	int ind = 0, j = i;
	while( j%2 == 0 ) {
		j /= 2;
		ind++;
	}
	return ind;
}

/*
 * Task: Implement C function that has the following signature:
 *    int** allocate_matrix( int i, int j );
 * the function will be used in the following code:
 *    int **a = allocate_matrix( 3, 2 );
 *    a[0][0] = 5;
 *    a[1][1] = 10;
 * Can you make it simpler???
 */
int** allocateMatrix( int i, int j ) {
	int **matrix = (int **)malloc( i*sizeof(int *) );
	for( int k = 0; k < i; k++ )
		matrix[k] = (int *)calloc( j, sizeof(int) );
	return matrix;
}

/*
 * Task: Write your implementation of the strcmp function
 * (don't use standard libraries).
 */
int myStrcmp( const char *s1, const char *s2 ) {
	int rc =0;
	const char *p2 = s2;
	for( const char *p1 = s1; *p1 != 0; p1++ ) {
		if( *p1 != *p2 ) {
			rc = *p1 > *p2 ? 1 : -1;
			break;
		}
		p2++;
	}
	if( rc == 0 && *p2 != 0 )
		rc = -1;
	return rc;
}

int main3() {
//	cout << "IsBigEndian: " << isBigEndian() << endl;
//	cout << "LeastSignificantSetBitIndex( " << 8 << ") = " << leastSignificantSetBitIndex( 8 ) << endl;
//	cout << "AllocateMatrix( 3, 2 ): " << endl;
//	int **m = allocateMatrix( 3, 2 );
//	m[0][0] = 5;
//	m[1][1] = 10;
//	for( int i = 0; i < 3; i++ )
//		for( int j = 0; j < 2; j++ )
//			cout << "M[" << i << "][" << j << "]=" << m[i][j] << endl;
//	for( int i = 0; i < 3; i++ )
//		free( m[i] );
//	free( m );
	const char *s1 = "abcd";
	const char *s2 = "Abcdef";
	cout << "MyStrcmp( " << s1 << ", " << s2 << ") = " << myStrcmp( s1, s2 ) << endl;
}
